<!-- pages/profile.vue -->
<template>
  <div class="profile-page">
    <h1 class="page-title">
      <UserOutlined />
      个人中心
    </h1>

    <a-row :gutter="24">
      <a-col :span="12">
        <!-- 个人信息卡片 -->
        <a-card title="个人信息" class="info-card" :bordered="false">
          <template #extra>
            <EditOutlined @click="showEditModal" />
          </template>
          <a-descriptions :column="1" size="small">
            <a-descriptions-item label="用户名">
              <UserOutlined />
              {{ authStore.currentUser?.username }}
            </a-descriptions-item>
            <a-descriptions-item label="邮箱">
              <MailOutlined />
              {{ authStore.currentUser?.email }}
            </a-descriptions-item>
            <a-descriptions-item label="注册时间">
              <CalendarOutlined />
              {{ formatDate(authStore.currentUser?.createdAt) }}
            </a-descriptions-item>
            <a-descriptions-item label="最后登录">
              <LoginOutlined />
              {{ formatDate(authStore.currentUser?.lastLoginAt) }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 技能标签区域 -->
        <a-card title="技能标签" class="skills-card" :bordered="false">
          <template #extra>
            <Tooltip title="添加新技能">
              <PlusCircleOutlined @click="showAddSkillModal" />
            </Tooltip>
          </template>
          
          <div class="skills-container">
            <div class="skills-grid">
              <div 
                v-for="skill in skills" 
                :key="skill.id" 
                class="skill-tag"
                :style="{ backgroundColor: getRandomColor(skill.id) }"
                @click="showEditSkillModal(skill)"
              >
                <TagOutlined class="skill-icon" />
                <span class="skill-name">{{ skill.name }}</span>
                <CloseCircleOutlined class="delete-icon" @click.stop="deleteSkill(skill.id)" />
              </div>

              <!-- 添加技能按钮 -->
              <div 
                v-if="skills.length < 15" 
                class="add-skill-btn" 
                @click="showAddSkillModal"
              >
                <PlusOutlined />
                <span>添加技能</span>
              </div>
            </div>

            <!-- 技能数量提示 -->
            <div class="skills-count">
              <InfoCircleOutlined />
              已添加 {{ skills.length }}/15 个技能标签
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="12">
        <!-- 设置区域 -->
        <a-card title="账户设置" class="settings-card" :bordered="false">
          <template #extra>
            <SettingOutlined />
          </template>
          
          <div class="settings-actions">
            <a-button type="primary" @click="showEditModal" size="large" class="edit-btn">
              <template #icon>
                <EditOutlined />
              </template>
              编辑个人信息
            </a-button>
            
            <a-button @click="showSecurityModal" size="large" class="security-btn">
              <template #icon>
                <SafetyOutlined />
              </template>
              安全设置
            </a-button>
          </div>

          <!-- 编辑历史记录 -->
          <div class="edit-history-section">
            <h3>
              <HistoryOutlined />
              编辑历史记录
            </h3>
            <a-table 
              :columns="historyColumns" 
              :data-source="editHistory" 
              :loading="historyLoading"
              :pagination="historyPagination" 
              size="small"
              class="history-table"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'fieldName'">
                  <span class="field-badge">
                    <FieldIcon :field="record.fieldName" />
                    {{ getFieldDisplayName(record.fieldName) }}
                  </span>
                </template>
                <template v-else-if="column.key === 'editedAt'">
                  <ClockCircleOutlined />
                  {{ formatDate(record.editedAt) }}
                </template>
                <template v-else-if="column.key === 'changes'">
                  <div class="changes-display">
                    <span class="old-value">{{ record.oldValue || '空' }}</span>
                    <ArrowRightOutlined />
                    <span class="new-value">{{ record.newValue || '空' }}</span>
                  </div>
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 编辑个人信息弹窗 -->
    <a-modal 
      v-model:visible="editModalVisible" 
      title="编辑个人信息" 
      :confirm-loading="editLoading" 
      @ok="handleEditSubmit"
      @cancel="handleEditCancel" 
      ok-text="保存" 
      cancel-text="取消"
      class="edit-modal"
    >
      <a-form ref="editFormRef" :model="editFormState" :rules="editFormRules" layout="vertical">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="editFormState.username" placeholder="请输入新的用户名" size="large">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="editFormState.email" placeholder="请输入新的邮箱地址" size="large">
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加技能弹窗 -->
    <a-modal 
      v-model:visible="addSkillModalVisible" 
      title="添加技能标签" 
      :confirm-loading="addSkillLoading"
      @ok="handleAddSkillSubmit" 
      @cancel="handleAddSkillCancel" 
      ok-text="确定" 
      cancel-text="取消"
      class="skill-modal"
    >
      <a-form ref="addSkillFormRef" :model="addSkillFormState" :rules="addSkillFormRules" layout="vertical">
        <a-form-item label="技能名称" name="skillName">
          <a-input 
            v-model:value="addSkillFormState.skillName" 
            placeholder="请输入技能名称（最多8个字符）" 
            size="large" 
            :maxlength="8"
            show-count
          >
            <template #prefix>
              <TagOutlined />
            </template>
          </a-input>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑技能弹窗 -->
    <a-modal 
      v-model:visible="editSkillModalVisible" 
      title="编辑技能标签" 
      :confirm-loading="editSkillLoading"
      @ok="handleEditSkillSubmit" 
      @cancel="handleEditSkillCancel" 
      ok-text="保存" 
      cancel-text="取消"
      class="skill-modal"
    >
      <a-form ref="editSkillFormRef" :model="editSkillFormState" :rules="editSkillFormRules" layout="vertical">
        <a-form-item label="技能名称" name="skillName">
          <a-input 
            v-model:value="editSkillFormState.skillName" 
            placeholder="请输入技能名称（最多8个字符）" 
            size="large" 
            :maxlength="8"
            show-count
          >
            <template #prefix>
              <TagOutlined />
            </template>
          </a-input>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 安全设置弹窗 -->
    <a-modal 
      v-model:visible="securityModalVisible" 
      title="安全设置" 
      @cancel="handleSecurityCancel"
      class="security-modal"
      :footer="null"
    >
      <div class="security-content">
        <a-alert message="安全设置功能开发中，敬请期待！" type="info" show-icon />
        <div class="security-features">
          <a-list item-layout="horizontal">
            <a-list-item>
              <template #actions>
                <a-button type="link" size="small">修改</a-button>
              </template>
              <a-list-item-meta
                title="密码修改"
                description="定期修改密码保障账户安全"
              >
                <template #avatar>
                  <LockOutlined />
                </template>
              </a-list-item-meta>
            </a-list-item>
            <a-list-item>
              <template #actions>
                <a-button type="link" size="small">设置</a-button>
              </template>
              <a-list-item-meta
                title="双重认证"
                description="启用双重认证提高安全性"
              >
                <template #avatar>
                  <SafetyOutlined />
                </template>
              </a-list-item-meta>
            </a-list-item>
          </a-list>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  UserOutlined,
  MailOutlined,
  EditOutlined,
  CalendarOutlined,
  LoginOutlined,
  TagOutlined,
  PlusOutlined,
  PlusCircleOutlined,
  CloseCircleOutlined,
  ArrowRightOutlined,
  SettingOutlined,
  SafetyOutlined,
  HistoryOutlined,
  ClockCircleOutlined,
  InfoCircleOutlined,
  LockOutlined,
  
} from '@ant-design/icons-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { message ,Tooltip} from 'ant-design-vue'

// 字段图标组件
const FieldIcon = ({ field }: { field: string }) => {
  const icons = {
    username: UserOutlined,
    email: MailOutlined
  }
  const IconComponent = icons[field as keyof typeof icons] || TagOutlined
  return h(IconComponent)
}

interface UserEditHistory {
  id: number
  fieldName: string
  oldValue: string
  newValue: string
  editedAt: string
  editedBy: number
}

interface Skill {
  id: number
  name: string
  createdAt: string
  updatedAt: string
}

const authStore = useAuthStore()

// 响应式数据
const editModalVisible = ref(false)
const editLoading = ref(false)
const historyLoading = ref(false)
const skillsLoading = ref(false)
const securityModalVisible = ref(false)

// 技能相关状态
const skills = ref<Skill[]>([])
const addSkillModalVisible = ref(false)
const addSkillLoading = ref(false)
const editSkillModalVisible = ref(false)
const editSkillLoading = ref(false)
const editingSkillId = ref<number | null>(null)

// 表单状态
const editFormRef = ref()
const editFormState = reactive({
  username: '',
  email: ''
})

const editFormRules: Record<string, Rule[]> = {
  username: [
    { required: false, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

const addSkillFormRef = ref()
const addSkillFormState = reactive({
  skillName: ''
})

const addSkillFormRules: Record<string, Rule[]> = {
  skillName: [
    { required: true, message: '请输入技能名称', trigger: 'blur' },
    { min: 1, max: 8, message: '技能名称不能超过8个字符', trigger: 'blur' }
  ]
}

const editSkillFormRef = ref()
const editSkillFormState = reactive({
  skillName: ''
})

const editSkillFormRules: Record<string, Rule[]> = {
  skillName: [
    { required: true, message: '请输入技能名称', trigger: 'blur' },
    { min: 1, max: 8, message: '技能名称不能超过8个字符', trigger: 'blur' }
  ]
}

// 编辑历史相关
const editHistory = ref<UserEditHistory[]>([])
const historyPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const historyColumns = [
  {
    title: '编辑字段',
    dataIndex: 'fieldName',
    key: 'fieldName',
    width: 100
  },
  {
    title: '变更内容',
    key: 'changes',
    width: 200
  },
  {
    title: '编辑时间',
    dataIndex: 'editedAt',
    key: 'editedAt',
    width: 150
  }
]

// 随机颜色生成器
const getRandomColor = (seed: number) => {
  const colors = [
    '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57',
    '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3', '#ff9f43',
    '#a29bfe', '#fd79a8', '#e17055', '#00b894', '#fdcb6e',
    '#e84393', '#0984e3', '#6c5ce7', '#00cec9', '#fab1a0'
  ]
  return colors[seed % colors.length]
}

// 字段显示名称映射
const getFieldDisplayName = (fieldName: string) => {
  const fieldMap: Record<string, string> = {
    'username': '用户名',
    'email': '邮箱'
  }
  return fieldMap[fieldName] || fieldName
}

// 显示编辑弹窗
const showEditModal = () => {
  editFormState.username = authStore.currentUser?.username || ''
  editFormState.email = authStore.currentUser?.email || ''
  editModalVisible.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    editLoading.value = true

    const token = authStore.token
    if (!token) {
      throw new Error('请先登录')
    }

    const response = await $fetch('/api/user/profile', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: editFormState
    })

    if (response.code === 200) {
      authStore.setUser(response.data)
      message.success('个人信息更新成功')
      editModalVisible.value = false
      fetchEditHistory()
    }
  } catch (error: any) {
    console.error('编辑个人信息失败:', error)
    message.error(error.data?.message || '更新失败')
  } finally {
    editLoading.value = false
  }
}

// 取消编辑
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value.resetFields()
}

// 获取技能列表
const fetchSkills = async () => {
  try {
    skillsLoading.value = true
    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      console.log('未登录或用户信息不存在')
      return
    }

    const response = await $fetch('/api/skills', {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      query: {
        username: currentUser.username
      }
    })

    if (response.code === 200) {
      skills.value = response.data
    }
  } catch (error: any) {
    console.error('获取技能列表失败:', error)
    message.error(error.data?.message || '获取技能列表失败')
  } finally {
    skillsLoading.value = false
  }
}

// 显示添加技能弹窗
const showAddSkillModal = () => {
  addSkillFormState.skillName = ''
  addSkillModalVisible.value = true
}

// 提交添加技能
const handleAddSkillSubmit = async () => {
  try {
    await addSkillFormRef.value.validate()
    addSkillLoading.value = true

    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      throw new Error('请先登录')
    }

    const response = await $fetch('/api/skills', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: {
        username: currentUser.username,
        skillName: addSkillFormState.skillName
      }
    })

    if (response.code === 201) {
      message.success('技能添加成功')
      addSkillModalVisible.value = false
      fetchSkills()
    }
  } catch (error: any) {
    console.error('添加技能失败:', error)
    message.error(error.data?.message || '添加失败')
  } finally {
    addSkillLoading.value = false
  }
}

// 取消添加技能
const handleAddSkillCancel = () => {
  addSkillModalVisible.value = false
  addSkillFormRef.value.resetFields()
}

// 显示编辑技能弹窗
const showEditSkillModal = (skill: Skill) => {
  editingSkillId.value = skill.id
  editSkillFormState.skillName = skill.name
  editSkillModalVisible.value = true
}

// 提交编辑技能
const handleEditSkillSubmit = async () => {
  try {
    await editSkillFormRef.value.validate()
    editSkillLoading.value = true

    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      throw new Error('请先登录')
    }

    // 临时实现：先删除再添加
    await $fetch(`/api/skills/${editingSkillId.value}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      query: {
        username: currentUser.username
      }
    })

    await $fetch('/api/skills', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: {
        username: currentUser.username,
        skillName: editSkillFormState.skillName
      }
    })

    message.success('技能更新成功')
    editSkillModalVisible.value = false
    fetchSkills()
  } catch (error: any) {
    console.error('编辑技能失败:', error)
    message.error(error.data?.message || '编辑失败')
  } finally {
    editSkillLoading.value = false
  }
}

// 取消编辑技能
const handleEditSkillCancel = () => {
  editSkillModalVisible.value = false
  editSkillFormRef.value.resetFields()
  editingSkillId.value = null
}

// 删除技能
const deleteSkill = async (skillId: number) => {
  try {
    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      message.error('请先登录')
      return
    }

    await $fetch(`/api/skills/${skillId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      query: {
        username: currentUser.username
      }
    })

    message.success('技能删除成功')
    fetchSkills()
  } catch (error: any) {
    console.error('删除技能失败:', error)
    message.error(error.data?.message || '删除失败')
  }
}

// 显示安全设置弹窗
const showSecurityModal = () => {
  securityModalVisible.value = true
}

// 取消安全设置
const handleSecurityCancel = () => {
  securityModalVisible.value = false
}

// 获取编辑历史
const fetchEditHistory = async () => {
  try {
    historyLoading.value = true
    const token = authStore.token
    if (!token) return

    const response = await $fetch('/api/user/edit-history', {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      query: {
        page: historyPagination.current,
        limit: historyPagination.pageSize
      }
    })

    if (response.code === 200) {
      editHistory.value = response.data.editHistory
      historyPagination.total = response.data.pagination.totalCount
    }
  } catch (error: any) {
    console.error('获取编辑历史失败:', error)
    message.error('获取编辑历史失败')
  } finally {
    historyLoading.value = false
  }
}

// 日期格式化
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchEditHistory()
    fetchSkills()
  }
})

// 监听认证状态变化
watch(() => authStore.isAuthenticated, (newVal) => {
  if (newVal) {
    fetchEditHistory()
    fetchSkills()
  }
})

useHead({
  title: '个人中心 - 系统控制台'
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  padding: 24px;
  background-image: url('~/assets/images/bgcar.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.page-title {
  text-align: center;
  color: #fff;
  font-size: 2.5rem;
  margin-bottom: 32px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.info-card,
.skills-card,
.settings-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
}

.info-card :deep(.ant-card-head),
.skills-card :deep(.ant-card-head),
.settings-card :deep(.ant-card-head) {
  border-bottom: 1px solid #e8e8e8;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.info-card :deep(.ant-card-extra),
.skills-card :deep(.ant-card-extra),
.settings-card :deep(.ant-card-extra) {
  color: white;
  cursor: pointer;
}

.settings-actions {
  margin-bottom: 32px;
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.edit-btn,
.security-btn {
  flex: 1;
  min-width: 200px;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.edit-history-section {
  margin-top: 24px;
}

.edit-history-section h3 {
  margin-bottom: 16px;
  color: #1890ff;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
}

.history-table :deep(.ant-table) {
  border-radius: 8px;
  overflow: hidden;
}

.field-badge {
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.changes-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.old-value {
  color: #ff4d4f;
  text-decoration: line-through;
}

.new-value {
  color: #52c41a;
  font-weight: bold;
}

/* 技能标签样式 */
.skills-container {
  padding: 8px 0;
}

.skills-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.skill-tag {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 80px;
  justify-content: center;
}

.skill-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.skill-icon {
  margin-right: 6px;
  font-size: 12px;
}

.skill-name {
  margin-right: 6px;
}

.delete-icon {
  font-size: 12px;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.delete-icon:hover {
  opacity: 1;
  color: #ff4d4f;
}

.add-skill-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border: 2px dashed #d9d9d9;
  border-radius: 20px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: all 0.3s ease;
  min-width: 100px;
}

.add-skill-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: rgba(24, 144, 255, 0.05);
}

.skills-count {
  font-size: 14px;
  color: #666;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

/* 模态框样式 */
.edit-modal :deep(.ant-modal-content),
.skill-modal :deep(.ant-modal-content),
.security-modal :deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

.edit-modal :deep(.ant-modal-header),
.skill-modal :deep(.ant-modal-header),
.security-modal :deep(.ant-modal-header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.edit-modal :deep(.ant-modal-title),
.skill-modal :deep(.ant-modal-title),
.security-modal :deep(.ant-modal-title) {
  color: white;
}

.security-content {
  padding: 16px 0;
}

.security-features {
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .profile-page {
    padding: 16px;
  }
  
  .ant-col-12 {
    width: 100%;
  }
  
  .settings-actions {
    flex-direction: column;
  }
  
  .edit-btn,
  .security-btn {
    min-width: 100%;
  }
}

@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
    margin-bottom: 24px;
  }
  
  .skills-grid {
    justify-content: center;
  }
  
  .skill-tag {
    min-width: 70px;
    font-size: 12px;
    padding: 6px 10px;
  }
}
</style>